package com.di.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.di.base.common.exception.BusinessException;
import com.di.base.dao.AccountTblDao;
import com.di.base.entity.AccountTbl;
import com.di.base.service.AccountTblService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * AccountTblService 实现类，支持 Saga 模式
 */
@Slf4j
@Service("accountTblService") // Bean 名称必须与 JSON 中的 ServiceName 一致
public class AccountTblServiceImpl extends ServiceImpl<AccountTblDao, AccountTbl> implements AccountTblService {

    @Resource
    private AccountTblDao accountTblDao;

    /**
     * Saga 模式减少账户余额方法 (被状态机调用)
     *
     * @return "SUCCESS" 表示成功，其他表示失败
     */
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void decrease(String userId, Double money) {
        log.info("Saga模式 - 开始减少账户余额, XID: {}", RootContext.getXID());
        try {
            AccountTbl accountTbl = accountTblDao.selectOne(new QueryWrapper<AccountTbl>().eq("user_id", userId));
            if (accountTbl == null) {
                log.error("Saga模式 - 账户不存在, userId: {}", userId);
                throw new BusinessException(500, "账户不存在");
            }
            if (accountTbl.getBalance().compareTo(money) < 0) {
                log.error("Saga模式 - 账户余额不足, userId: {}, money: {}", userId, money);
                throw new BusinessException(500, "账户余额不足");
            }
            accountTbl.setBalance(accountTbl.getBalance() - money);
            accountTblDao.updateById(accountTbl);
            log.info("Saga模式 - 账户余额减少成功");
        } catch (Exception e) {
            log.error("Saga模式 - 减少账户余额异常", e);
            throw new BusinessException(500, e.getMessage()); // 或者 return "EXCEPTION";
        }
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void increase(String userId, Double money) {
        log.info("Saga模式 - 开始补偿账户余额增加, XID: {}", RootContext.getXID());

        try {
            AccountTbl accountTbl = accountTblDao.selectOne(new QueryWrapper<AccountTbl>().eq("user_id", userId));
            accountTbl.setBalance(accountTbl.getBalance() + money);
            // 执行补偿逻辑：增加账户余额
            accountTblDao.updateById(accountTbl);
            log.info("Saga模式 - 账户余额补偿增加成功");
        } catch (BusinessException e) {
            log.error("Saga模式 - 补偿账户余额增加异常", e);
            throw new BusinessException(500, e.getMessage()); // 或者 return "EXCEPTION";
        }
    }
}